<template>
  <div>
    <van-index-bar :index-list="indexlist">
      <div v-for="(data,index) in datalist" :key="index">
        <van-index-anchor  :index="data.index">{{data.index}}</van-index-anchor>
       <van-cell v-for="(item,index) in data.list" :key="index" :title="item.name" @click="handleClick(item)"/>
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import http from '@/util/http'
import Vue from 'vue'
import { mapMutations } from 'vuex'
import { IndexBar, IndexAnchor, Cell } from 'vant'
Vue.use(IndexBar).use(IndexAnchor).use(Cell)
export default {
  data () {
    return {
      indexlist: [],
      datalist: []
    }
  },
  mounted () {
    http.request({
      url: 'gateway?k=3256290',
      headers: {
        'X-Host': 'mall.film-ticket.city.list'
      }
    }).then(res => {
      // 向zimuarray方法传入获取到的数组
      this.zimuarray(res.data.data.cities)
    })
  },
  methods: {
    zimuarray (citys) {
      var letterArr = []
      for (var i = 65; i < 91; i++) {
        letterArr.push(String.fromCharCode(i))
      }
      console.log(letterArr)

      // filter 遍历26个字母， 跟citys数据.pinyin.首字母.大写 进行过滤
      var cityArr = []
      for (let j = 0; j < letterArr.length; j++) {
        var temparr = citys.filter(item =>
          item.pinyin.substring(0, 1).toUpperCase() === letterArr[j])
        // temparr不为空,将当前字母和首字母相同的城市添加到cityArr
        temparr.length && cityArr.push({
          index: letterArr[j],
          list: temparr
        })
        // temparr不为空，将存在的将当前字母存入indexlist
        temparr.length && this.indexlist.push(letterArr[j])
      }
      this.datalist = cityArr
    },
    // city命名空间中，取出setCityName,setCityId
    handleClick (item) {
      // 传递name  cityid 到vuex存储
      this.setCityName(item.name)
      this.setCityId(item.cityId)
      this.$router.back()
    },
    ...mapMutations('city', ['setCityName', 'setCityId'])
  }
}
</script>
